//
//  ViewController.swift
//  CyclicCard
//
//  Created by Tony on 17/1/11.
//  Copyright © 2017年 Tony. All rights reserved.
//

import UIKit

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

    let bgview = UIView()
    var collectionView : UICollectionView!
    let showLabel = UILabel()
    let currentLabel = UILabel()
    
    let groupCount = 100 // 制造100组数据，给无限滚动提供足够多的数据，嫌少可以200，1000。。。
    var imageArr = [String]() // 图片数组
    var indexArr = [Int]() // 存储图片下标，解决制造100组图片数据占用过大内存问题
    var timer:Timer?
    var layout = CyclicCardFlowLayout()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        makeUI()
        
        // 设置数据源
        imageArr = ["num_1", "num_2", "num_3", "num_4", "num_5"]
        for _ in 0 ..< groupCount {
            for j in 0 ..< imageArr.count {
                indexArr.append(j)
            }
        }
        
        // 定位到 第50组(中间那组)
        collectionView.scrollToItem(at: NSIndexPath.init(item: groupCount / 2 * imageArr.count, section: 0) as IndexPath, at: UICollectionView.ScrollPosition.centeredHorizontally, animated: false)
        
        addTimer()
    }
    
    // MARK:- UI
    func makeUI() {
        
        automaticallyAdjustsScrollViewInsets = false
        
        var navigationAndStatusBarHeight = 64
        if SCREEN_HEIGHT >= 812.0 {
            navigationAndStatusBarHeight = 88
        }
        bgview.frame = CGRect(x: 0, y: CGFloat(navigationAndStatusBarHeight), width: SCREEN_WIDTH, height: FIT_SCREEN_HEIGHT(240))
        bgview.backgroundColor = MAIN_COLOR()
        self.view.addSubview(bgview)
        
        setupCollection()
        
        showLabel.frame = CGRect(x: 0, y: bgview.bottom + FIT_SCREEN_HEIGHT(20), width: SCREEN_WIDTH, height: FIT_SCREEN_HEIGHT(20))
        showLabel.textAlignment = NSTextAlignment.center
        showLabel.text = "滚动至第1张"
        view.addSubview(showLabel)
        
        currentLabel.frame = CGRect(x: 0, y: showLabel.bottom + FIT_SCREEN_HEIGHT(20), width: SCREEN_WIDTH, height: FIT_SCREEN_HEIGHT(20))
        currentLabel.textAlignment = NSTextAlignment.center
        currentLabel.text = "点击第 张图片"
        view.addSubview(currentLabel)
    }
    
    func setupCollection() {
        
        let padding = FIT_SCREEN_WIDTH(20)
        
        layout.scrollDirection = .horizontal
        
        //水平流布局中，minimumLineSpacing表示列与列之间的最小间距
        layout.minimumLineSpacing = padding * 2
        
        //设置内边距
//        layout.sectionInset = UIEdgeInsets(top: padding, left: 0, bottom: padding, right: 0)
        let itemW = (SCREEN_WIDTH - padding * 2) * 1
        layout.itemSize = CGSize(width: itemW, height: bgview.height - padding * 2)
        let paddingLR = (SCREEN_WIDTH - itemW)/2
        layout.sectionInset = UIEdgeInsets(top: 0, left: paddingLR, bottom: 0, right: paddingLR)
        
        collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: bgview.height), collectionViewLayout: layout)
        collectionView.backgroundColor = UIColor.clear
        collectionView.collectionViewLayout = layout
        collectionView.showsHorizontalScrollIndicator = false
        // 加快减速（默认是缓慢减速）
        collectionView.decelerationRate = UIScrollViewDecelerationRateFast
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(CyclicCardCell.self, forCellWithReuseIdentifier: NSStringFromClass(CyclicCardCell.self))
        bgview.addSubview(self.collectionView)
    }
    
    
    // MARK:- CollectionView
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return indexArr.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(CyclicCardCell.self), for: indexPath) as! CyclicCardCell
        print("indexPath.row", indexPath.row);
        let index = indexArr[indexPath.row]
        cell.index = index
        cell.cardImgView.image = UIImage(named: imageArr[index])
        cell.cardNameLabel.text = "奔跑吧，小蜗牛~"
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath) as! CyclicCardCell
        print("点击第\(cell.index + 1)张图片")
        currentLabel.text = "点击第\(cell.index + 1)张图片"
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        
        //注释（by hong），pointInView其实就是collectionView.contentOffset.x + collectionView.frame.size.width/2
        let pointInView = view.convert(collectionView.center, to: collectionView)
        print("pointInView", pointInView)
        let indexPathNow = collectionView.indexPathForItem(at: pointInView)
        let index = (indexPathNow?.row ?? 0) % imageArr.count
        let curIndexStr = String(format: "滚动至第%d张", index + 1)
        print(curIndexStr)
        showLabel.text = curIndexStr
        
        // 动画停止, 重新定位到 第50组(中间那组) 模型
        collectionView.scrollToItem(at: NSIndexPath.init(item: groupCount / 2 * imageArr.count + index, section: 0) as IndexPath, at: UICollectionViewScrollPosition.centeredHorizontally, animated: false)
        print("collectionView.offset.x", collectionView.contentOffset.x);
        
        addTimer()
    }
    
    
    //by hong
    func addTimer() {
        removeTimer()
        
        timer = Timer.scheduledTimer(timeInterval: 4, target: self, selector: #selector(nextImage), userInfo: nil, repeats: true)
    }
    
    func removeTimer() {
        timer?.invalidate()
        timer = nil;
    }
    
    @objc func nextImage() {
        let offsetX = collectionView.contentOffset.x + layout.itemSize.width + layout.minimumLineSpacing
        collectionView.setContentOffset(CGPoint.init(x: offsetX, y: 0), animated: true)
        
        let itemIndex = offsetX / (layout.itemSize.width + layout.minimumLineSpacing)
        let indicatorIndex = Int(itemIndex) % imageArr.count
        let curIndexStr = String(format: "滚动至第%d张", indicatorIndex + 1)
        showLabel.text = curIndexStr
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        removeTimer()
    }
    
//    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
//
//        let collectionContentCenterX = collectionView.contentOffset.x + collectionView.frame.size.width * 0.5;
//        print("collectionView.visibleCells:\(collectionView.visibleCells)")
//        var miniOffsetX = CGFloat(MAXFLOAT)
//        var indexPath:IndexPath?
//        for cell in collectionView.visibleCells {
//            if abs(collectionContentCenterX - cell.center.x) < miniOffsetX {
//                miniOffsetX = cell.center.x - collectionContentCenterX
//                indexPath = collectionView.indexPath(for: cell)!
//            }
//        }
//        var offsetX = collectionView.contentOffset.x + miniOffsetX
//        let indexPathRow = indexPath!.row
//        print("========index:\(indexPathRow)")
//        let itemWidthAndSpacing = layout.itemSize.width + layout.minimumLineSpacing
//
////         velocity.x = 0，表示手指没有向左也没有向右，垂直离开屏幕
////         velocity.x < 0，表示手指向右滑动
////         velocity.x > 0，表示手指向左滑动
//
//        if velocity.x < 0 { //向右滑动
//            offsetX = CGFloat(indexPathRow-1) * itemWidthAndSpacing - (SCREEN_WIDTH/2 - layout.itemSize.width/2)
//            targetContentOffset.pointee.x = offsetX
//        }else if velocity.x > 0 { //向左滑动
//            offsetX = CGFloat(indexPathRow+1) * itemWidthAndSpacing - (SCREEN_WIDTH/2 - layout.itemSize.width/2)
//            targetContentOffset.pointee.x = offsetX
//        }else {
//            scrollView.setContentOffset(CGPoint.init(x: offsetX, y: 0), animated: true)
//        }
//    }
}

